package main

import (
	"fmt"
	"io"
	"net"
	"time"
	"zinx/ziface"
	"zinx/znet"
)

func main() {
	fmt.Println("client start...")
	time.Sleep(1 * time.Second)
	//1.直接连接远程服务器，得到一个conn连接
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client start err: ", err)
		return
	}
	for {
		//2.发送封包的msg消息
		dp := znet.NewDatapack()
		binaryMsg, err := dp.Pack(znet.NewMessage(1, []byte("ZinxV0.7 client test msg")))
		if err != nil {
			fmt.Println("Pack error: ", err)
			return
		}
		if _, err := conn.Write(binaryMsg); err != nil {
			fmt.Println("Write error: ", err)
			return
		}
		//3.服务器应该给我们回复一个message数据，需要处理
		binaryHead := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, binaryHead); err != nil {
			fmt.Println("Read head error: ", err)
			break
		}
		var msgHead ziface.IMessage
		if msgHead, err = dp.Unpack(binaryHead); err != nil {
			fmt.Println("Unpack head error: ", err)
			break
		}
		if msgHead.GetMsgLen() > 0 {
			//有数据，二次读
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetMsgLen())
			if _, err := io.ReadFull(conn, msg.Data); err != nil {
				fmt.Println("Read msg data error: ", err)
				return
			}
			fmt.Println("---> Recv Server Msg: Id = ", msg.Id, " len = ", msg.GetMsgLen(), " data = ", string(msg.GetData()))
		}
		//阻塞
		time.Sleep(1 * time.Second)
	}
}
